package com.zhi.service;

import com.zhi.domain.MiaoshaOrder;
import com.zhi.domain.MiaoshaUser;
import com.zhi.domain.OrderInfo;
import com.zhi.redis.MiaoshaKey;
import com.zhi.redis.RedisService;
import com.zhi.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author WenZhi Luo
 * @version 1.0
 * @date 2020/2/5 16:23
 */
@Service
public class MiaoshaService {
    private Logger logger = LoggerFactory.getLogger(MiaoshaService.class);
    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    RedisService redisService;

    /**
     * 只要有一步出问题，就会回滚...  原子性操作
     */
    @Transactional
    public OrderInfo miaosha(MiaoshaUser user, GoodsVo goods) {
        //减库存 下订单 写入秒杀订单,
        boolean success = goodsService.reduceStock(goods);
        if(success) {
            //order_info maiosha_order
            return orderService.createOrder(user, goods);
        }else {
            //上述操作失败，说明商品卖完了
            setGoodsOver(goods.getId());
            return null;
        }
    }
    public long getMiaoshaResult(Long userId, long goodsId) {
        //获取订单消息，如果成功获取到了就说明创建订单成功，即秒杀成功
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(userId, goodsId);
        if(order != null) {//秒杀成功
            return order.getOrderId();
        }else {
            //判断商品是否卖完
            boolean isOver = getGoodsOver(goodsId);
            if(isOver) {
                return -1;
            }else {
                //商品没卖完，继续排队ing
                return 0;
            }
        }
    }

    private void setGoodsOver(Long goodsId) {
        redisService.set(MiaoshaKey.isGoodsOver, ""+goodsId, true);
    }

    private boolean getGoodsOver(long goodsId) {
        return redisService.exists(MiaoshaKey.isGoodsOver, ""+goodsId);
    }

    public void reset(List<GoodsVo> goodsList) {
        goodsService.resetStock(goodsList);
        orderService.deleteOrders();
    }
}
